import 'package:file_picker/file_picker.dart';
import 'package:flutter_app/network/Loading.dart';
import 'package:flutter_app/utils/video_compress_utils.dart';
import 'package:image_pickers/image_pickers.dart';

/**
 * @Description: 文件选择器
 * @Author: 下雨了
 * @CreateDate: 2022-06-16 17:20
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-06-16 17:20
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
//
// dependencies:
//   file_picker: ^4.6.1
//
///
class FilePickerUtils {
  // 私有构造函数
  FilePickerUtils._internal();

  // 保存单例
  static final FilePickerUtils _filePickerUtils = FilePickerUtils._internal();

  // 工厂构造函数
  factory FilePickerUtils() => _filePickerUtils;

  FilePicker initFilePicker() {
    FilePicker filePicker = FilePicker.platform;
    return filePicker;
  }

  Future<List<Media>?> pickFiles() async {
    Loading.show();
    FilePickerResult? result = await initFilePicker().pickFiles(
      type: FileType.media,
      allowMultiple: true,
    );
    List<Media> list = [];
    if (result != null) {
      for (PlatformFile file in result.files) {
        Media media = new Media();
        media.path = file.path;
        media.name = file.name;
        if (file.path!.contains('jpeg') ||
            file.path!.contains('jpg') ||
            file.path!.contains('png'))  {
          media.galleryMode = GalleryMode.image;
        } else {
          media.galleryMode = GalleryMode.video;
          final thumbnailFile = await VideoCompressUtils().getFileThumbnail(file.path ?? "");
          media.thumbPath = thumbnailFile.path;
        }
        list.add(media);
      }
    }
    Loading.dismiss();
    return list;
  }

  /// Selects a directory and returns its absolute path.
  /// 选择目录并返回其绝对路径。
  Future<String?> getDirectoryPath() async {
    String? selectedDirectory = await initFilePicker().getDirectoryPath();
    return selectedDirectory;
  }

  /// Opens a save file dialog which lets the user select a file path and a file name to save a file.
  /// 打开一个保存文件对话框，用户可以选择文件路径和文件名来保存文件。
  Future<String?> saveFile() async {
    String? file = await initFilePicker().saveFile();
    return file;
  }
}
